package com.ChenYaRou.www.controller;

import com.ChenYaRou.www.constant.JsonBeanConstant;
import com.ChenYaRou.www.dao.FoodDao;
import com.ChenYaRou.www.dao.ShopDao;
import com.ChenYaRou.www.dao.impl.FoodDapImpl;
import com.ChenYaRou.www.dao.impl.ShopDaoImpl;
import com.ChenYaRou.www.po.Food;
import com.ChenYaRou.www.utils.JsonBean;
import com.ChenYaRou.www.po.Shop;
import com.alibaba.fastjson.JSON;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName GetAllShopFoodController
 * @Description TODO
 * @Author 86183
 * @Date 2022/4/30 18:11
 * @Version 1.0
 **/
public class GetAllShopFoodServletController {
    /**
     * 获得所有店铺与其对应的美食
     *
     * @return 搜索出结果的json 或 ‘这里空空如也呢~’
     */
    public String getAllShopFood() {
        ShopDao shopDao = new ShopDaoImpl();
        StringBuilder json = new StringBuilder();
        List<Shop> shops ;
        try {
            shops = shopDao.selectAll(new Shop());
            if (shops != null && !shops.isEmpty()) {
                HashMap<String, Object> hashMap = new HashMap<>(1024);
                json.append("[");
                for (Shop shop : shops) {
                    hashMap.put("Shop", shop);
                    FoodDao dao = new FoodDapImpl();
                    Food food = new Food();
                    food.setShopId(shop.getId());
                    List<Food> foods = dao.selectMore(food);
                    System.out.println(foods);
                    if (foods != null) {
                        hashMap.put("Foods", foods);
                        json.append(JSON.toJSONString(hashMap)).append(",");
                    }
                }
                json.delete(json.lastIndexOf(","), json.length()).append("]");
                //因为data过于复杂 于是手动json...
                return "{\"code\":" + JsonBeanConstant.GET + ",\"data\":" + json +
                        ",\"state\":\"" + JsonBeanConstant.SUCCESS + "\"}";
            }
        } catch (IllegalAccessException | SQLException |
                NoSuchFieldException | InstantiationException e) {
            e.printStackTrace();
        }
        return JsonBean.operateList(JsonBeanConstant.NULL,null);
    }
}
